package cn.edu.tsinghua.mutimedia.image.extract;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

//
import liredemo.indexing.MetadataBuilder;
import liredemo.indexing.ParallelIndexer;
import net.semanticmetadata.lire.DocumentBuilder;
import net.semanticmetadata.lire.utils.LuceneUtils;

import org.apache.hadoop.fs.Path;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;

import cn.edu.tsinghua.mutimedia.util.Conf;

import java.util.ArrayList;

public class ExtractVideo {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) {
		try
		{
			String videofile = "test.mp4";
			if(args.length > 0)
			{
				videofile = args[0];
			}
			Path path = new Path(videofile);
			String shortName= path.getName();
			videofile =Conf.LOCAL_AUDIO_DIR+shortName;
			
			String imageFormat = "JPG";
			openMyExe("md I-Frames");	
			String cmd = "ffmpeg -i \"%s\" -vf select='eq(pict_type,I)' -vsync 0 I-Frames/%d.%s";
			cmd = String.format(cmd, videofile, imageFormat);
			openMyExe(cmd);	
			File directory = new File(".");
			ExtractImageCharacter(directory.getAbsolutePath()+"I-Frames");
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
    public static void ExtractImageCharacter(String imagePath) {
        try {
            
            java.util.ArrayList<java.lang.String> images =
                    getAllImages(
                            new java.io.File(imagePath), true);
            if (images == null) {
				System.out.println("Could not find any files");
                return;
            }
            IndexWriter iw;
            iw = LuceneUtils.createIndexWriter(imagePath, false);

            int count = 0;
            Document doc;
            DocumentBuilder builder = new MetadataBuilder();
            ParallelIndexer indexer = new ParallelIndexer(images, builder);
            new Thread(indexer).start();

            while ((doc = indexer.getNext()) != null) {
                try {
                    iw.addDocument(doc);
                } catch (Exception e) {
                    System.err.println("Could not add document.");
                    e.printStackTrace();
                }
                count++;
            }
            System.out.println("Finished indexing ...");
            iw.commit();
            iw.close();

        } catch (IOException ex) {
            System.err.println("Error catched!S");
        }
    }
    public static ArrayList<String> getAllImages(File directory, boolean descendIntoSubDirectories) throws IOException {
        ArrayList<String> resultList = new ArrayList<String>(256);
        File[] f = directory.listFiles();
        for (File file : f) {
            if (file != null && (file.getName().toLowerCase().endsWith(".jpg") || file.getName().toLowerCase().endsWith(".png")) && !file.getName().startsWith("tn_")) {
                resultList.add(file.getCanonicalPath());
            }
            if (descendIntoSubDirectories && file.isDirectory()) {
                ArrayList<String> tmp = getAllImages(file, true);
                if (tmp != null) {
                    resultList.addAll(tmp);
                }
            }
        }
        if (resultList.size() > 0)
            return resultList;
        else
            return null;
    }	
	
    public static void openMyExe(String execmd) {  
       Runtime rn = Runtime.getRuntime();  
       Process p = null;  
       try {  
           p = rn.exec(execmd); 
           InputStream is = p.getInputStream();
           BufferedReader reader = new BufferedReader(new InputStreamReader(is));
           String line;
           while((line=reader.readLine())!=null)
           {System.out.println(line);};
           p.waitFor();
           is.close();
           reader.close();
           p.destroy();
           System.out.println("Audio Extracted");
           
       } catch (Exception e) {  
           System.out.println("Error my exec ");  
       }  
    }  
	
	
	

}


